import getopt
import getpass
import sys
import time

import gdata.apps.service


class DeleteUsersSample(object):

	def __init__(self,admin_account,admin_password,domain,string):
		self.client = gdata.apps.service.AppsService()
		self.client.domain = domain
		self.client.email = admin_account
		self.client.password = admin_password
		self.client.ProgrammaticLogin()
		self.startString = string


	def Run(self):
		# Retrieve all users
		count=0
		userList = self.client.RetrieveAllUsers()
		
		# Iterate through UserFeed object
		for userEntry in userList.entry:
			print
			if (userEntry.login.user_name[:len(self.startString)] == self.startString):
				print '%i Deleting user: ' % count +  userEntry.login.user_name+'@'+self.client.domain
				count=count+1
				try:
					#delete the user
					time.sleep(2)
					self.client.DeleteUser(userEntry.login.user_name)
				except gdata.service.RequestError, e:
					print 'There was an error deleting user: ' + userEntry.login.user_name
					raise AppsForYourDomainException(e.args[0])			
		print 'Number of users deleted = %i' %count
	
def main():
# Command line Parameters:
	try:
		opts, args = getopt.getopt(sys.argv[1:], '', ['admin_account=', 'admin_password=', 'domain=', 'start_string='])
	except getopt.error, msg:
		print 'python togglePasswordChangeOff.py --admin_account [admin account name] --admin_password [password]'
		print ' --domain [yourdomain.com]'
		sys.exit(2)

	admin_account = ''
	admin_password = ''
	domain = ''
	startString = ''

	# Process the Command Line Args
	for option, arg in opts:
		if option == '--admin_email':
			admin_email = arg
		elif option == '--admin_password':
 			admin_password = arg
		elif option == '--domain':
			domain = arg
		elif option == '--start_string':
			startString = arg

	# Make sure input parameters are available
	while not domain:
		domain = raw_input('Enter your Google Apps domain (i.e. "yourname.com"): ')
		if not domain:
			print 'domain name cannot be blank'
	while not admin_account:
		admin_account = raw_input('Enter a administrator account: ')+'@'+domain
		if not admin_account:
			print 'User name cannot be blank'
	while not admin_password:
		admin_password = getpass.getpass('Enter the admin account password: ')
		if not admin_password:
			print 'Password cannot be blank'
	if not startString:
		startString = raw_input('Enter the starting string: ')
	while not startString:
		print 'An empty start string will delete all the accounts. You want to continue (y/n)'
		response  = raw_input()
		if response == 'y':
			break
		elif response != 'n':
			print 'Unrecognized response'
		startString = raw_input('Enter the starting string: ')
		
 
	# Authenticate the password toggle service
	try:
		DeleteUserService = DeleteUsersSample(admin_account, admin_password, domain, startString)
	except gdata.service.BadAuthentication:
		print 'Invalid user credentials given.'
		return

	DeleteUserService.Run()
 
if __name__ == "__main__":
    main()
